package cn.kgc.controller;

import cn.kgc.entity.Item;
import cn.kgc.pojo.ItemQuery;
import cn.kgc.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class ItemController {
    @Autowired
    private ItemService itemService;

    //查询所有分类
//    @GetMapping("/item")
//    public String getAllItem(Model model){
//        List<Item> itemList =itemService.getAllItem();
//        model.addAttribute("ItemList",itemList);
//        return "ItemList";
//    }

    //跳转到分类页面
    @GetMapping("/item/view")
    public String toAddItem(Model model){

        model.addAttribute("item", new Item());

        //查询pid分类
        List<Item> itemList =itemService.getAllItem();
        model.addAttribute("ItemList",itemList);
        return "item";
    }

    //新增
    @PostMapping("/item")
    public String addItem(Item item){
        itemService.addItem(item);
        return "redirect:/item";
    }

    //根据Id查询
    @GetMapping("/item/{id}")
    public String getItemById(@PathVariable("id") Integer id,Model model){
        Item item = itemService.getItemById(id);
        model.addAttribute("item",item);

        List<Item> itemList =itemService.getAllItem();
        model.addAttribute("ItemList",itemList);
        return "item";
    }

    //修改
    @PutMapping("/item")
    public String updateItem(Item item){
        itemService.updateItem(item);
        return "redirect:/item";
    }

    //删除
    @DeleteMapping("/item/{id}")
    public String deleteItem(@PathVariable("id") Integer id){
        itemService.deleteItemById(id);
        return "redirect:/item";
    }


    //带分页查询
    @GetMapping("/item")
    public String getItemList(ItemQuery param, Model model){
        if (null == param.getPageNo()) {
            param.setPageNo(1);
        }
        if (null == param.getPageSize()) {
            param.setPageSize(3);
        }

        List<Item> itemList =itemService.getItemList(param);
        model.addAttribute("ItemList",itemList);
        model.addAttribute("query",param);
        Integer count = itemService.countItem();
        Integer totalPage = count%param.getPageSize() == 0 ? count/param.getPageSize() : count/param.getPageSize()+1;
        model.addAttribute("totalPage",totalPage);
        return "ItemList";
    }

    //查询pid数量判断是否存在
    @GetMapping("/item/pid/{id}")
    @ResponseBody
    public String countPid(@PathVariable("id") Long pid) {
        Integer countPid = itemService.countPid(pid);
        return countPid.toString();
    }
}
